package cate.game.res.revelry;

import cate.common.table.d.GDFunc;
import cate.common.table.d.GDOperation;
import cate.common.table.res.revelry.RevelryBaseRow;
import cate.common.util.GameResult;
import cate.game.res.MixRes;
import cate.game.res.MixResAdder;
import cate.game.res.revelry.msg.RevelryDrawResp;
import cate.game.role.FuncOpenChecker;
import cate.game.role.Role;
import cate.game.role.RoleDependent;
import com.fasterxml.jackson.annotation.JsonIgnore;
import cp.solution.util.time.TimeSpanCheck;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class RevelryDraw extends FuncOpenChecker {
    @NoteField(value = "上次登录的时间")
    public long lastLoginTime;

    @NoteField(value = "领取状态<天数，是否领取>")
    public Map<Integer, Boolean> gotMap;

    @JsonIgnore
    @NoteField(value = "是否全部领取")
    public boolean allGot;

    @JsonIgnore
    @NoteField(value = "领取天数")
    public int gotDay;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (gotMap == null) {
            gotMap = new HashMap<>();
        }
    }

    @Override
    public void onEnter() {
        super.onEnter();
        if (allGot) {
            return;
        }
        if (TimeSpanCheck.spanDay(lastLoginTime)) {
            lastLoginTime = game().time.now();
            gotDay ++;
            gotMap.put(gotDay, false);
        }

    }

    @Override
    public int getFuncId() {
        return GDFunc.REVELRY;
    }

    @Override
    public void onAfterOpen() {
        noticeUpdate();
    }

    public void noticeUpdate() {
        if (!allGot && open) {
            role.sendNow(new RevelryDrawResp(this));
        }
    }

    public GameResult<Void> showReward(int day) {
        GameResult<Void> r = new GameResult<>();
        if (!gotMap.containsKey(day)) {
            return r.fail("当前天数未登录");
        }
        if (gotMap.get(day)) {
            return r.fail("已领取");
        }
        RevelryBaseRow baseRow = role.getGame().table.revelry.base.get(day);
        if (baseRow == null || StringUtils.isBlank(baseRow.rewardStr)) {
            return r.fail("奖励未配置");
        }
        MixRes reward = new MixRes(baseRow.rewardStr);
        // 发放奖励
        EcResult<?> exe = new MixResAdder().setRes(reward)
                .setOperation(GDOperation.REVELRY)
                .setDialogReward(true)
                .setSendMailWhenFull(true)
                .exe(role);
        gotMap.put(day, true);
        noticeUpdate();
        checkAllGot();
        return r;
    }

    private void checkAllGot() {
        if (gotDay < 30) {
            return;
        }
        allGot = true;
        for(boolean rewardGot : gotMap.values()) {
            if (!rewardGot) {
                allGot = false;
                break;
            }
        }
    }
}
